<template>
  <div class="user">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-form
        size="small"
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
      >
        <el-form-item label="关键词">
          <el-input
            v-model="formInline.keyword"
            placeholder="请输入车主姓名|车主电话|车牌号搜索"
          ></el-input>
        </el-form-item>
        <el-form-item label="预约地区">
          <el-cascader v-model="formInline.booking_region" :options="regions" />
        </el-form-item>
        <!-- <el-form-item label="所属门店">
          <el-select v-model="formInline.store_id" filterable
          remote
          placeholder="输入用户ID/昵称/姓名/手机号进行搜索"
          remote-show-suffix
          :remote-method="searchUser"
          :loading="search_loading"
          style="width: 240px"
          default-first-option>
            <el-option label="全部" :value="-1"></el-option>
            <el-option label="未分配" :value="0"></el-option>
            <el-option
              v-for="(item, index) in storeOption"
              :key="index"
              :label="item.real_name"
              :value="item.user_id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="预约时间">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
              v-model="formInline.create_at"
              type="daterange"
              value-format="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getTableInfo(1)"
            >查询</el-button
          >
          <el-button
            type="primary"
            icon="Plus"
            @click="exportExcel()"
            v-auth="'/user/user/add'"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-tabs v-model="store_status" class="demo-tabs">
        <el-tab-pane label="待分配" name="0"></el-tab-pane>
        <el-tab-pane label="已分配" name="1"></el-tab-pane>
      </el-tabs>
    </div>
    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-table
          size="small"
          :data="tableData"
          border
          height="calc(100vh - 300px)"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column
            prop="booking_id"
            label="ID"
            width="80"
          ></el-table-column>
          <el-table-column prop="owner_name" label="车主姓名"></el-table-column>
          <el-table-column
            prop="owner_phone"
            label="车主电话"
          ></el-table-column>
          <el-table-column prop="license_plate" label="车牌号" />
          <el-table-column
            prop="booking_location"
            label="预约地区"
          ></el-table-column>
          <el-table-column
            prop="store.real_name"
            label="所属门店"
          ></el-table-column>
          <el-table-column prop="created_at" label="预约时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="370" fixed-right>
            <template #default="scope">
              <el-button
                @click="setStore(scope.row)"
                link
                type="primary"
                size="small"
                v-auth="'/carfilm/order/edit'"
                v-if="scope.row.store_id == 0"
                >分配门店
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--分页-->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :current-page="curPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalDataNumber"
        ></el-pagination>
      </div>
    </div>
    <table id="hidden-table" class="hidden-table">
      <thead>
        <tr>
          <th>车主姓名</th>
          <th>车主电话</th>
          <th>车牌号</th>
          <th>预约地区</th>
          <th>所属门店</th>
          <th>预约时间</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in allData" :key="index">
          <td>{{ item.owner_name }}</td>
          <td>{{ item.owner_phone }}</td>
          <td>{{ item.license_plate }}</td>
          <td>{{ item.booking_location }}</td>
          <td>{{ item.store_name }}</td>
          <td>{{ getLocalTime(item.created_at) }}</td>
        </tr>
      </tbody>
    </table>
    <el-dialog
      title="分配门店"
      v-model="dialogVisible"
      draggable
      center
      width="30%"
      @close="closeDialog"
    >
      <el-select v-model="setStoreId" filterable
          remote
          placeholder="输入用户ID/昵称/姓名/手机号进行搜索"
          remote-show-suffix
          :remote-method="searchUser2"
          :loading="search_loading2"
          default-first-option>
        <el-option
          v-for="(item, index) in regionStore"
          :key="index"
          :label="item.real_name"
          :value="item.user_id"
        >
        </el-option>
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setStoreSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { getRegionOption } from "@/api/utils";
import { getListAPi, setStoreApi } from "@/api/carfilm/order";
import { ElMessage } from "element-plus";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import { getUserOption } from "@/api/user";
const loading = ref(true);
const tableData = ref<any[]>([]);
const pageSize = ref(20);
const totalDataNumber = ref(0);
const curPage = ref(1);
const dialogVisible = ref(false);
const setStoreId = ref("");
const storeRegion = ref(0);
const booking_id = ref(0);
const formInline = ref({
  keyword: "",
  booking_region: [0],
  store_id: 0,
  create_at: [],
});
const store_status = ref("0");
const search_loading = ref(false);
const search_loading2 = ref(false);
const storeOption = ref<any[]>([]);
const regionStore = ref<any[]>([]);
const regions = ref<any[]>([
  {
    value: 0,
    pid: 0,
    label: "全国",
  },
]);
watch(store_status,(newval:string)=>{
  getTableInfo(1);
})
onMounted(() => {
  getRegionOption().then((res: any) => {
    if (res.code == 1) {
      regions.value = [...regions.value, ...res.data];
    }
  });
  getTableInfo(1);
});
const searchUser = (query: string) => {
  if (query !== "") {
    search_loading.value = true;
    getUserOption({
      keyword: query,
    }).then((res: any) => {
      if (res.code == 1) {
        storeOption.value = res.data;
        search_loading.value = false;
      }
    });
  } else {
    storeOption.value = [];
  }
};
const searchUser2 = (query: string) => {
  if (query !== "") {
    search_loading2.value = true;
    getUserOption({
      keyword: query,
    }).then((res: any) => {
      if (res.code == 1) {
        regionStore.value = res.data;
        search_loading2.value = false;
      }
    });
  } else {
    regionStore.value = [];
  }
};
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getTableInfo(1);
};
const handleCurrentChange = (val: number) => {
  curPage.value = val;
  getTableInfo(val);
};
function getTableInfo(page: number) {
  loading.value = true;
  getListAPi({
    page: page,
    page_size: pageSize.value,
    ...formInline.value,
    status: store_status.value,
  }).then((res: any) => {
    tableData.value = res.data?.data;
    totalDataNumber.value = res.data?.total;
    loading.value = false;
  });
}
const allData = ref<any[]>([]);
function exportExcel() {
  loading.value = true;
  getListAPi({
    page: 1,
    page_size: 1000,
    ...formInline.value,
  }).then((res: any) => {
    allData.value = res.data?.data;
    tableData.value = allData.value.slice(0, pageSize.value);
    totalDataNumber.value = res.data?.total;
    //渲染完成后直行
    setTimeout(() => {
      // 获取表格元素
      const tableElement = document.querySelector("#hidden-table");
      if (!tableElement) {
        console.error("未读取到数据");
        return (loading.value = false);
      }

      // 将表格元素转换为工作表
      const worksheet = XLSX.utils.table_to_sheet(tableElement);
      processWorksheet(worksheet);
      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });

      // 创建Blob对象
      const blob = new Blob([excelBuffer], {
        type: "application/octet-stream",
      });
      //文件名
      const date = new Date();
      const filename = `车膜订单${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}.xlsx`;
      // 保存文件
      saveAs(blob, filename);
      loading.value = false;
    }, 500);
  });
}

const processWorksheet = (worksheet: any) => {
  const range = XLSX.utils.decode_range(worksheet["!ref"]);
  for (let R = range.s.r; R <= range.e.r; ++R) {
    for (let C = range.s.c; C <= range.e.c; ++C) {
      const cellRef = XLSX.utils.encode_cell({ r: R, c: C });
      const cell = worksheet[cellRef];

      if (cell) {
        // 处理数字字符串，确保不被转换为科学技术数字格式
        if (typeof cell.v === "number") {
          cell.t = "s"; // 设置为字符串类型
          cell.v = "'" + cell.v; // 在数字字符串前添加单引号
        }
        // 处理红色文字样式
        /*const element = document.querySelector(`#hidden-table tr:nth-child(${R + 1}) td:nth-child(${C + 1})`);
        if (element && element.classList.contains("red-text")) {
          if (!cell.s) {
            cell.s = {};
          }
          cell.s.font = {
            color: { rgb: "FF0000" } // 设置红色
          };
          console.log(`Cell ${cellRef} set to red text`);
        }*/
      }
    }
  }
  worksheet["!ref"] = XLSX.utils.encode_range(range);
};
function setStore(row: any) {
  if (row.store_id > 0) {
    return ElMessage.warning("该订单已分配门店");
  }
  storeRegion.value = row.booking_region;
  booking_id.value = row.booking_id;
  dialogVisible.value = true;
}
const closeDialog = () => {
  dialogVisible.value = false;
  storeRegion.value = 0;
  booking_id.value = 0;
  setStoreId.value = "";
};
const setStoreSubmit = () => {
  setStoreApi({
    booking_id: booking_id.value,
    store_id: setStoreId.value,
  }).then((res: any) => {
    ElMessage.success("设置成功");
    closeDialog();
    getTableInfo(curPage.value);
  });
};
const getLocalTime = (time_str: string) => {
  let res = time_str?.split(" ");
  let date = res[0] ?? "";
  date = date.replace("-", "年");
  date = date.replace("-", "月");
  let time = res[1] ?? "";
  return `${date}日 ${time}`;
};
</script>
<style>
.hidden-table {
  display: none;
}
</style>
